package org.example.managere.controller.feibiao;

import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.example.managere.dto.feibiao.AmAapInputDto;
import org.example.managere.service.feibiao.AmAapInputService;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/feibiao/aap/input")
@RequiredArgsConstructor
public class AmAapInputController {
    private final AmAapInputService service;

    /**
     * 分页查询
     */
    @GetMapping("/list")
    public Page<AmAapInputDto> list(@RequestParam(defaultValue = "0") int page,
                                    @RequestParam(defaultValue = "10") int size,
                                    @RequestParam(defaultValue = "id,desc") String sort) {
        String[] sortArr = sort.split(",");
        Pageable pageable = PageRequest.of(page, size, Sort.by(Sort.Direction.fromString(sortArr[1]), sortArr[0]));
        return service.findAll(pageable);
    }

    /**
     * 条件搜索（支持关键词）
     */
    @GetMapping("/search")
    public Page<AmAapInputDto> search(@RequestParam(required = false) String keyword,
                                      @RequestParam(defaultValue = "0") int page,
                                      @RequestParam(defaultValue = "10") int size,
                                      @RequestParam(defaultValue = "id,desc") String sort) {
        String[] sortArr = sort.split(",");
        Pageable pageable = PageRequest.of(page, size, Sort.by(Sort.Direction.fromString(sortArr[1]), sortArr[0]));
        return service.search(keyword, pageable);
    }

    /**
     * 新增
     */
    @PostMapping
    public AmAapInputDto create(@Valid @RequestBody AmAapInputDto dto) {
        return service.save(dto);
    }

    /**
     * 更新
     */
    @PutMapping("/{id}")
    public AmAapInputDto update(@PathVariable Integer id, @Valid @RequestBody AmAapInputDto dto) {
        return service.update(id, dto);
    }

    /**
     * 详情
     */
    @GetMapping("/{id}")
    public AmAapInputDto detail(@PathVariable Integer id) {
        return service.findById(id).orElseThrow(() -> new RuntimeException("记录不存在"));
    }

    /**
     * 删除
     */
    @DeleteMapping("/{id}")
    public void delete(@PathVariable Integer id) {
        service.deleteById(id);
    }
} 